<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use think\Cache;
use think\Exception;
use app\admin\model\User;
use fast\Random;

class Wechat extends Api
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';

    // 微信小程序配置
    private $appid = 'wx3b21db4197eacb5f';
    private $secret = '557b6a2f1a4435c769a4a194a17c5c24';

    /**
     * 微信小程序登录
     */
    public function login()
    {
        $code = $this->request->param('code');
        $encryptedData = $this->request->param('encryptedData');
        $iv = $this->request->param('iv');

        if (!$code) {
            $this->error('缺少code参数');
        }

        try {
            // 1. 获取微信session_key和openid
            $wxResult = $this->getWxSessionKey($code);
            $openid = $wxResult->openid;
            $sessionKey = $wxResult->session_key;

            // 2. 解密用户信息
            $userInfo = $this->decryptData($encryptedData, $iv, $sessionKey);

            if (!$userInfo) {
                $this->error('用户信息解密失败');
            }

            // 3. 查找或创建用户
            $user = $this->getOrCreateUser($openid, $userInfo);

            // 4. 生成token
            $token = $this->generateToken($user->id);

            // 5. 返回结果
            $this->success('登录成功', [
                'token' => $token,
                'userInfo' => [
                    'id' => $user->id,
                    'nickname' => $user->nickname,
                    'avatar' => $user->avatar,
                    'openid' => $openid
                ]
            ]);

        } catch (Exception $e) {
            $this->error('登录失败: ' . $e->getMessage());
        }
    }

    /**
     * 检查登录状态
     */
    public function checkLogin()
    {
        $this->success('登录状态有效', ['user' => $this->auth->getUser()]);
    }

    /**
     * 获取微信session_key和openid
     */
    private function getWxSessionKey($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session";

        // 使用ThinkPHP内置的Http客户端发送请求
        $response = Http::get($url, [
            'appid' => $this->appid,
            'secret' => $this->secret,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ]);

        // 将JSON响应转换为数组
        return json_decode($response);
    }

    /**
     * 解密用户信息
     */
    private function decryptData($encryptedData, $iv, $sessionKey)
    {
        if (strlen($sessionKey) != 24) {
            return false;
        }
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return false;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return false;
        }
        if ($dataObj->watermark->appid != $this->appid) {
            return false;
        }
        return $dataObj;
    }

    /**
     * 查找或创建用户
     */
    private function getOrCreateUser($openid, $userInfo)
    {
        // 查找是否已有该openid的用户
        $user = User::where('openid', $openid)->find();

        if (!$user) {
            // 创建新用户
            $user = new User();
            $user->username = 'wx_' . Random::alnum(10);
            $user->password = md5(123456); // 随机密码
            $user->openid = $openid;
            $user->mobile = $userInfo->phoneNumber;
            $user->save();
        } else {
            $user->password = md5(123456); // 随机密码
            $user->mobile = $userInfo->phoneNumber;
            $user->save();
        }

        return $user;
    }

    /**
     * 生成token
     */
    private function generateToken($userId)
    {
        $token = Random::uuid();
        // 存储token，有效期7天
        Cache::set('token_' . $token, $userId, 7 * 24 * 3600);
        return $token;
    }
}
